const router = require('koa-router')()
const Mock = require('mockjs')
const dataAll = require('./data')

router.prefix('/product')

let dataList = {}
let productIds = []
let detailList = {}

const mockIds = Mock.mock({
  'result|20-30': [{
    'id': '@increment'
  }]
})

const mockImages = [
  Mock.mock('@image(750x350, @color)'),
  Mock.mock('@image(750x480, @color)'),
  Mock.mock('@image(750x640, @color)'),
  Mock.mock('@image(750x750, @color)'),
  Mock.mock('@image(750x1000, @color)')
]


mockIds.result.map(item => {
  let list = generateList()
  dataList[item.id] = list
})

for (const [key, value] of Object.entries(dataList)) {
  if (dataList[key] && dataList[key].result.length) {
    let ids = []
    dataList[key].result.map(item => {
      ids.push(item.id)
    })
    productIds = [...productIds, ...ids]
  }
}

productIds.map(item => {
  detailList[item] = generateDetailList()
})

function generateList () {
  return Mock.mock({
    'name': '@county()',
    'banner': '@image(570x340, @color)',
    'result|9-30': [{
      'id': '@id',
      'image': '@image(80x80, @color)',
      'county': '@county()'
    }]
  })
}

function generateDetailList () {
  return Mock.mock({
    'region': '@region',
    'county': '@county(true)',
    'desc': '@cparagraph(2, 5)',
    'images|2-7': ['@image(750x480, @color)'],
    'detail': Mock.Random.pick(mockImages, 2, 4)
  })
}

function getCategories () {
  let result = []
  for (const [ key, value ] of Object.entries(dataList)) {
    result.push({
      id: key,
      name: dataList[key].name
    })
  }
  return result
}

function getList (key) {
  let result = dataList[key] || {}
  return result
}

function getDetail (id) {
  let result = detailList[id] || {}
  return result
}

function getProvince (dataList) {
  let provinceList = []
  // 遍历数据
  for (const [key, value] of Object.entries(dataList)) {
    if(value.province && value.province.length) {
      value.province.map(province => {
        provinceList.push({
          region: value.region,
          id: province.id,
          banner: province.image,
          name: province.name
        })
      })
    }
  }
  return provinceList
}

router.get('/categories', async (ctx, next) => {
  ctx.body = {
    code: 20000,
    data: {
      result: getCategories()
    }
  }
})

router.get('/list', async (ctx, next) => {
  ctx.body = {
    code: 20000,
    data: getList(ctx.query.id)
  }
})

router.get('/detail', async (ctx, next) => {
  ctx.body = {
    code: 20000,
    data: getDetail(ctx.query.productId)
  }
})

router.get('/all', async (ctx, next) => {
  ctx.body = {
    data: dataAll
  }
})

router.get('/province', async (ctx, next) => {
  ctx.body = {
    data: getProvince(dataAll)
  }
})

module.exports = router